import TaskRunner from 'concurrent-tasks';
import XEUtils from 'xe-utils';
import utils from "@common/utils/utils";
import Queue from "@common/utils/Queue";
import { message } from '@common/assets/js/resetMessage';
import { Loading } from 'element-ui';
import { genPrintData } from "./print";

let loading = undefined;
const showLoading = (text) => {
	if (!text) {
		text = '加载中...';
	}
	closeLoading();
	loading = Loading.service({
		lock: true,
		text,
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.5)',
		customClass: 'tsd_loading',
	});
};
const closeLoading = () => {
	if (loading) {
		loading.close();
	}
};
const doPrint = async (runner, done, printTemplate, i, item, options, retryTimes, printData) => {
	showLoading(`正在准备打印第 ${ i + 1 } 张...`);
	if (!printData) {
		let result = await options.fetchData(item);
		if (XEUtils.isArray(result)) {
			printData = result.map(t => genPrintData(options.template, t));
		} else if (XEUtils.isObject(result)) {
			printData = genPrintData(options.template, result);
		}
	}
	if (!printData) {
		done();
		return;
	}
	console.log('打印数据', printData);
	printTemplate.print2(printData, { printer: options.printer, title: `task${ i }` });
	printTemplate.on('printSuccess', function () {
		done();
	});
	printTemplate.on('printError', function () {
		closeLoading();
		message.error(`打印失败，已加入重试队列，剩余重试次数：${ retryTimes }`);
		if (retryTimes > 0) {
			runner.add(async () => {
				retryTimes -= 1;
				await doPrint(runner, done, printTemplate, i, item, options, retryTimes, printData);
			});
		}
		done();
	});
};
const genTaskList = (runner, printTemplate, list, options, retryTimes) => {
	let taskList = [];
	for (let i = 0; i < list.length; i++) {
		const item = list[i];
		taskList.push(async done => {
			await doPrint(runner, done, printTemplate, i, item, options, retryTimes)
		});
	}
	return taskList;
};
export const HiPrint = (printTemplate, options) => {
	if (!utils.isNotEmpty(options.template)) {
		message.error('缺少参数：template');
		return;
	}
	if (!utils.isNotEmptyList(options.dataList)) {
		message.error('参数：dataList 为空');
		return;
	}
	if (typeof options.fetchData === 'undefined') {
		message.error('缺少参数：fetchData');
		return;
	}
	let list = options.dataList;
	if (typeof options.eachData === 'function') {
		list = options.eachData(options.dataList);
		if (!list) {
			message.error('参数：eachData 处理逻辑有误');
			return;
		}
	}
	let retryTimes = 4;
	if (utils.isNotEmpty(options.retryTimes)) {
		retryTimes = options.retryTimes;
	}
	return new Promise(resolve => {
		const runner = new TaskRunner({
			// 同时执行数量
			concurrency: 1,
			// 是否自动执行
			autoStart: true,
		});
		let taskList = genTaskList(runner, printTemplate, list, options, retryTimes);
		if (!utils.isNotEmptyList(taskList)) {
			return
		}
		let queue = new Queue();
		taskList.forEach(task => {
			queue.enqueue(task);
		});
		runner.add(queue.dequeue());
		const interval = setInterval(() => {
			if (queue.isEmpty() && !runner.isBusy()) {
				message.success('已完成打印');
				clearInterval(interval);
				closeLoading();
				resolve(true);
			} else {
				if (!runner.isBusy()) {
					const task = queue.dequeue();
					runner.add(task);
				}
			}
		}, 1000);
	});
};